<script setup lang="ts">
  import { editOrgDetail, getOrgDetail } from '@/api/syssetting';
  import { FormInstance, Message } from '@arco-design/web-vue';
  import { cloneDeep, omit } from 'lodash';
  import { ref, watch } from 'vue';
  import { getpolicyIndex } from '@/api/dataCenter';
  import { getgeoarea, getgeocity, getGeoProvice } from '@/api/policy';
  import useLoading from '@/hooks/loading';
  const flag = ref(true);
  const props = defineProps({
    visible: Boolean,
    isEdit: Boolean,
    editParam: Object,
    industryAll: Array,
    directionAll: Array,
  });
  const { loading, setLoading } = useLoading(false);
  const emit = defineEmits(['update:visible', 'refresh']);
  const close = () => {
    emit('update:visible', false);
  };
  const formData = reactive({});
  watch(
    () => props.editParam,
    async (newVal) => {
      try {
        // 清除旧数据
        if (newVal) {
          const res = await getOrgDetail({ org_id: newVal });
          Object.assign(formData, res.data);
        }
      } catch (error) {}
    },
    { immediate: true } // 初始化时立即执行一次
  );

  const formRef = ref<FormInstance | null>(null);

  const handleSubmit = async () => {
    if (!(await formRef.value?.checkForm())) {
      try {
        setLoading(true);
        const dataForm = formRef.value?.formModel;
        editOrgDetail({
          org_id: props.editParam,
          ...omit(
            dataForm,
            'policy_direction_id',
            'policy_industry_id',
            'policy_field_id',
            'province_name',
            'city_name',
            'area_name',
            'create_time',
            'update_time',
            'delete_time',
            'org_field_name',
            'org_direction_name',
            'org_industry_name'
          ),
        }).then((res) => {
          Message.success(res.msg);
          emit('refresh', cloneDeep(formData));
          close();
        });
        Message.success(res.msg);
        emit('update:visible', false);
        emit('refresh');
      } catch (error) {
        setLoading(false);
      } finally {
        setLoading(false);
      }
    } else {
      Message.error('请正确填写表单！');
    }
  };

  const type = [
    {
      label: '单位名称',
      name: 'org_name',
      fieldProps: {
        placeholder: '请输入',
        allowClear: true,
        maxLength: 50,
      },
      tooltip: '软件注册后，请不要随意修改单位名称，这会导致需要重新注册',
      rules: [
        {
          required: true,
          message: '单位名称不能为空',
          validateTrigger: ['input'],
        },
        {
          maxLength: 50,
          message: '不能超过50个字符',
          validateTrigger: ['input'],
        },
      ],
    },
    {
      name: 'org_direction_id',
      label: '政策方向',
      type: 'a-select',
      selectOptions: props.directionAll,
      fieldProps: {
        span: 24,
        fieldNames: { value: 'direction_id', label: 'direction_name' },
        allowSearch: true,
        placeholder: '请选择',
      },
      rules: [
        {
          required: true,
          message: '请选择',
        },
      ],
    },
    {
      name: 'org_industry_id',
      label: '政策行业',
      type: 'a-select',
      selectOptions: props.industryAll,
      fieldProps: {
        span: 24,
        fieldNames: { value: 'industry_id', label: 'industry_name' },
        allowSearch: true,
        placeholder: '请选择',
      },
      rules: [
        {
          required: true,
          message: '请选择',
        },
      ],
    },
    {
      name: 'org_field_id',
      label: '政策领域',
      type: 'a-select',
      selectOptions: [],
      fieldProps: {
        span: 24,
        fieldNames: { value: 'field_id', label: 'field_name' },
        allowSearch: true,
        placeholder: '请选择',
      },
      rules: [
        {
          required: true,
          message: '请选择',
        },
      ],
    },
    {
      name: 'province_id',
      label: '省',
      type: 'a-select',
      fieldProps: {
        span: 24,
        allowSearch: true,
        fieldNames: { value: 'id', label: 'name' },
      },
      selectOptions: [],
      rules: [
        {
          message: '请选择',
          required: true,
        },
      ],
    },
    {
      name: 'city_id',
      label: '市',
      type: 'a-select',
      fieldProps: {
        span: 24,
        allowSearch: true,
        placeholder: '请选择',
        fieldNames: { value: 'id', label: 'name' },
      },
      selectOptions: [],
      rules: [
        {
          message: '请选择',
          required: true,
        },
      ],
    },
    {
      name: 'area_id',
      label: '区县',
      type: 'a-select',
      fieldProps: {
        span: 24,
        fieldNames: { value: 'id', label: 'name' },
        allowSearch: true,
      },
      selectOptions: [],
      rules: [
        {
          message: '请选择',
          required: true,
        },
      ],
    },
    {
      label: '机构代码',
      name: 'org_code',
      rules: [
        {
          required: true,
          message: '请输入',
          validateTrigger: ['blur'], // Arco 推荐触发方式
        },
      ],
      fieldProps: {
        placeholder: '请输入',
        allowClear: true,
        maxLength: 200,
      },
    },
    {
      label: '电话',
      name: 'org_contact',
      rules: [
        {
          required: true,
          message: '请输入',
          validateTrigger: ['blur'], // Arco 推荐触发方式
        },
      ],
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      label: '地址',
      name: 'org_address',
      fieldProps: {
        placeholder: '请输入',
      },
      rules: [
        {
          required: true,
          message: '请输入',
          validateTrigger: ['blur'], // Arco 推荐触发方式
        },
      ],
    },
    {
      label: '官方网站',
      name: 'org_website',
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      label: '电子邮件',
      name: 'org_email',
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      label: '邮政编码',
      name: 'org_postal_code',
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      label: '银行账号',
      name: 'org_account_num',
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      label: '开户银行',
      name: 'org_account_bank',
      fieldProps: {
        placeholder: '请输入',
      },
    },
  ];
  const formFields = ref();
  const provice = ref();
  const allpolicyarea = ref();
  onMounted(() => {
    getpolicyIndex({
      page_size: 10000,
    }).then((allpolicy) => {
      getGeoProvice().then((pro) => {
        provice.value = pro.data;
        allpolicyarea.value = allpolicy.data.list;
        type[3].selectOptions = allpolicyarea.value;
        type[4].selectOptions = provice.value;
        formFields.value = type;
      });
    });
  });
  const city = ref();
  // 监听省变化
  watch(
    () => formRef.value?.formModel.province_id,
    (newVal) => {
      getgeocity({
        province_id: newVal,
      }).then((res) => {
        if (!flag) {
          formRef.value?.setFormItm('area_id', '');
          formRef.value?.setFormItm('city_id', '');
          city.value = res.data;
          type[5].selectOptions = res.data;
          formFields.value = type;
        } else {
          city.value = res.data;
          type[5].selectOptions = res.data;
          formFields.value = type;
          flag.value = false;
        }
      });
    }
  );

  // 监听市变化 - 添加标志位判断
  watch(
    () => formRef.value?.formModel.city_id,
    (newVal) => {
      // 初始化过程中不执行watch逻辑
      if (newVal) {
        getgeoarea({
          city_id: newVal,
        }).then((res) => {
          if (!flag) {
            formRef.value?.setFormItm('area_id', '');
            type[6].selectOptions = res.data;
            formFields.value = type;
          } else {
            type[6].selectOptions = res.data;
            formFields.value = type;
            flag.value = false;
          }
        });
      }
    }
  );
</script>
<script lang="ts">
  export default {
    name: 'company',
  };
</script>

<template>
  <a-modal
    title="修改机构"
    width="600px"
    :visible="visible"
    @ok="handleSubmit"
    title-align="start"
    :ok-loading="loading"
    @cancel="emit('update:visible', false)"
  >
    <pro-form
      ref="formRef"
      hiddenBtn
      :form-json="formFields"
      :form-data="formData"
    ></pro-form>
  </a-modal>
</template>

<style scoped lang="less"></style>
